/**
 * 
 */
package org.nielin.bestwaper.core;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nielin.wap.actions.Action;
import org.nielin.util.log.MyLogger;
import org.nielin.util.profiling.UtilTimerStack;

/**
 * @author rockydai
 *
 */
public class Controller extends WebEntity {
	private String actionClassName;
    private Action action;
	private Map<String,String> resultMap;
	
	public static final String CONTROLLER_RESULT_PAGE_ID  = "controllerResultPageId";
	
	public Controller( String id, String className, Map<String, String> resultMap ) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		this.id = id;
		actionClassName = className;
        action = (Action)Class.forName(className).newInstance();
        action.setId( id );
		this.resultMap = resultMap;
	}
	
    public void go(WebEntityContext context) {
        if ( !validate(context) )
        {
            return;
        }
        
        HttpServletRequest req = context.getRequest();
        HttpServletResponse res = context.getResponse();
        
		try
		{		
            String profileMsg = actionClassName+".execute";
            UtilTimerStack.push(profileMsg);
			String status = action.execute( context );
            UtilTimerStack.pop(profileMsg);
			
			if ( status.equals("") )
			{
                String errorMsg = "action[" + actionClassName + "] return empty status!";
				throw new Exception(errorMsg);
			}
			else
			{
				MyLogger.getNormal().debug( "action[" + actionClassName + "] return status[" + status + "]" );				
			}
			
			if ( status.equals(Action.HASDISPATCHERED) ) {
				return;
			}
			
			String resultId = resultMap.get( status );
			
			// 保存controll的结果页面的id，filter的chain之后可能要用到
			req.setAttribute( CONTROLLER_RESULT_PAGE_ID, resultId );
			
			if ( resultId == null || resultId.equals("") )
			{
			    if ( status.equals("Error") ) {
			        // Error是特殊状态，允许不配置
			        resultId = "error";
			    }
			    else {
	                String errorMsg = "action[" + actionClassName + "] has no status[" + status + "]";
	                throw new Exception(errorMsg);			        
			    }

			}
			
			WebEntity dest = DispatcherMap.getInstance().getEntity( resultId );
			if ( dest == null )
			{
				String errorMsg = "action[" + actionClassName + "] status[" + status + "]" + " dest to id[" + resultId + "], but id is not exist!";
                throw new Exception(errorMsg);
			}
			
            WebEntityContext context2 = new WebEntityContext();
            context2.setRequest( req );
            context2.setResponse( res );
            context2.setId(getId());
            profileMsg = "WebEntity.go, id[" + resultId + "]";
            UtilTimerStack.push(profileMsg);  
            req.setAttribute( "id", resultId );
			dest.go( context2 );
            UtilTimerStack.pop(profileMsg);            
		}
		catch(Exception e2)
		{
		    ErrorPageBean errorpage = new ErrorPageBean("页面 id[" + getId() + "]跳转失败！");
            MyLogger.getNormal().error("[" + errorpage.getErrno() + "]" + e2.getMessage(), e2);
		    Dispatcher.toErrorPage(req, res, errorpage);
		}
		
	}
}
